package com.navi168.fwq21.util;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.za.communication.core.codec.decoder.DataSegmentationDecoder;
import org.za.communication.core.codec.encoder.DataCombineEncoder;
import org.za.communication.core.handler.SessionIdleHandler;
import org.za.communication.message.GetVerifyCodeMessage;
import org.za.communication.message.RegisterMessage;

import com.amap.mapapi.core.GeoPoint;
import com.navi168.fwq21.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity {
	private static String TAG = "mylog";
	private EditText username;
	private EditText password;
	private EditText password2;
	private EditText moblie;
	private EditText code;
	private Button getcode;
	private Button reg;
	private Button cance;
	private TimeCount time;
	private ProgressDialog progDialog;
	private SessionIdleHandler sessionIdleHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reg);

		findviews();
		setlistens();
		time = new TimeCount(60000, 1000, getcode);
	}

	private void setlistens() {
		getcode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				time.start();

			}
		});
		reg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toReg();

			}
		});

	}

	private void findviews() {
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		password2 = (EditText) findViewById(R.id.password2);
		moblie = (EditText) findViewById(R.id.mobile);
		code = (EditText) findViewById(R.id.Authenticode);
		getcode = (Button) findViewById(R.id.getcodebutton);
		reg = (Button) findViewById(R.id.regbutton);
		cance = (Button) findViewById(R.id.cancebutton);
		progDialog = new ProgressDialog(this);

	}

	private void toReg() {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				socketServer();
			}
		});
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("注册信息提交中...");
		progDialog.show();
		thread.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.REG_OK) {

				progDialog.dismiss();
				showToast("恭喜您！注册成功！");
				Intent intent = new Intent(Register.this, Login.class);
				startActivity(intent);
				Register.this.finish();

			}
			if (msg.what == Constants.REG_NO) {

				progDialog.dismiss();
				showToast("您之前已注册过！");

			}
			if (msg.what == Constants.REG_PASS) {

				progDialog.dismiss();
				showToast("密码格式错误，请修正！");

			}
			if (msg.what == Constants.REG_OTHER) {

				progDialog.dismiss();
				showToast("SORRY！请稍候再试...");

			}

		}
	};

	private void socketServer() {
		sessionIdleHandler = new SessionIdleHandler();
		byte[] head = new byte[2];
		head[0] = (byte) 0xff;
		head[1] = (byte) 0xff;

		List<Integer> l = new ArrayList<Integer>();// 需要加密
		l.add(0x01);
		l.add(0x02);
		l.add(0x03);
		l.add(0x05);
		l.add(0x06);
		List<Integer> l2 = new ArrayList<Integer>();// 需要解密
		l2.add(0x04);
		l2.add(0x52);
		l2.add(0x53);
		l2.add(0x54);

		DataCombineEncoder encoder = new DataCombineEncoder();
		encoder.setHead(head);
		encoder.setEncryptIdList(l);

		DataSegmentationDecoder decoder = new DataSegmentationDecoder();
		decoder.setHead(head);
		decoder.setDecryptIdList(l2);

		IoConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(30000);

		connector.getFilterChain().addLast("mycodec",
				new ProtocolCodecFilter(encoder, decoder));
		connector.setHandler(sessionIdleHandler);
		ConnectFuture future = connector.connect(new InetSocketAddress(
				"tsp.navi168.com", 9123));
		future.awaitUninterruptibly();
		IoSession session = future.getSession();
		// 获取密钥
		GetVerifyCodeMessage message = new GetVerifyCodeMessage();
		// 注册的类
		RegisterMessage rMessage = new RegisterMessage();
		try {
			session.write(message);// 发送获取密钥信息
			byte[] key = new byte[4];
			// 通过sessionidlehandler 获取全局变量
			boolean gogo = true;

			while (gogo) {// 循环为了确保获取密钥
				if (sessionIdleHandler.go) {// 那边如果确定获得密钥就让 go为true。开始注册流程。
					Log.i(TAG, "可以获取key了");
					key = sessionIdleHandler.key;
					gogo = false;
					sessionIdleHandler.go = false;

				}
			}
			rMessage.setName(username.getText().toString());
			rMessage.setCode(code.getText().toString());
			rMessage.setPhone(moblie.getText().toString());
			rMessage.setKey(key);
			rMessage.setPassword(password.getText().toString());
			session.write(rMessage);
			while (true) {

				if (sessionIdleHandler.flag != "") {

					String flag = sessionIdleHandler.flag;
					Log.i(TAG, "SessionIdleHandler.flag-"
							+ sessionIdleHandler.flag + "-");
					if (flag == "ok" && flag.equals("ok")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.REG_OK));

					} else if (flag == "no" && flag.equals("no")) {

						handler.sendMessage(Message.obtain(handler,
								Constants.REG_NO));
					} else if (flag == "pass" && flag.equals("pass")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.REG_PASS));
					} else if (flag == "other" && flag.equals("other")) {
						handler.sendMessage(Message.obtain(handler,
								Constants.REG_OTHER));
					}
					sessionIdleHandler.flag = "";
					break;
				}

			}

		} catch (Exception ee) {
			System.out.println(ee);
		}

	}

	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}

}
